#coding:utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')

import hashlib
import re
import dbs


class Users(object):
	"""docstring for user"""
	def __init__(self):
		self.conn, self.cur = dbs.db_connect()

	#用户是否存在
	def esxit_phone(self,phone):
		query = '''
			SELECT 
				phone 
			FROM 
				users 
			WHERE phone='{phone}'
		'''.format(phone=phone)
		try:
			if self.cur.execute(query):
				return True #用户存在
			else:
				return False #用户不存在
		except Exception as e:
			raise e

	def check_qq(self,qq):
		ret = True if re.match('[1-9][0-9]{4,9}$', qq) else False
		return ret

	def check_username(self,username):
		ret = True if re.match('^[a-zA-Z][a-zA-Z0-9_]{4,16}$', username) else False
		return ret

	def check_phone(self,phone):
		ret = True if re.match('^1[3,4,5,7,8][0-9]{9}$',phone) else False
		return ret

	def login(self,user_info):
		if ('phone' and 'passwd') not in user_info:
			return {'code' : 5, 'message' : '提交参数不全'}
		if not self.check_phone(phone=user_info['phone']):
				return {'code' : 6, 'message' : '手机号码格式错误'}

		query = '''
			SELECT 
				phone,passwd,status,username 
			FROM 
				users
			WHERE
				phone='{phone}'
		'''.format(phone=user_info['phone'])
		try:
			if not self.cur.execute(query):
				return {'code' : 1, 'message' : '用户不存在'}
			phone, db_passwd, status, username = self.cur.fetchone()
			if not status:
				return {'code' : 2, 'message' : '用户未激活'}
			if ( hashlib.md5(user_info['passwd']).hexdigest() == db_passwd ):
				return {'code' :0, 'message' : 'success', 'username' : username}
			else:
				return {'code' : 3, 'message' : '密码错误'}

		except Exception as e:
			raise e
		finally:
			self.cur.close(); self.conn.close()

	def register(self,user_info):
		if ( 'username' and 'phone' and 'passwd' and 'cls_type' and 'num' ) in user_info:
			phone = user_info['phone']
			if not self.check_phone(phone=phone):
				return {'code' : 6, 'message' : '手机号码格式错误'}
			if not self.check_username(username=user_info['username']):
				return {'code' : 7, 'message' : '用户名格式错误'}
			if 'qq' in user_info:
				if not self.check_qq(qq=user_info['qq']):
					return {'code' : 8, 'message' :'qq格式错误'}
				else:
					qq = user_info['qq']
			else:
				qq = 0

			if self.esxit_phone(phone=phone):
				self.conn.close()
				return {'code' : 4, 'message' : '用户名已注册，请更换用户名'}

			sex = user_info['sex'] if 'sex' in user_info else 0
			passwd = hashlib.md5(user_info['passwd']).hexdigest()
			query = '''
				INSERT INTO
					users(username, phone, passwd, sex, qq, cls_type, num)
				VALUES('{username}','{phone}','{passwd}','{sex}','{qq}','{cls_type}','{num}')
			'''.format(username=user_info['username'],
					   phone=user_info['phone'],
					   passwd=passwd,
					   sex=sex,
					   qq=qq,
					   cls_type=user_info.get('cls_type','python'),
					   num=user_info.get('num',1))

			try:
				self.cur.execute(query)
				self.conn.commit()
				return {'code' : 0, 'message' : '注册成功'}
			except Exception as e:
				raise e
			finally:
				self.cur.close(); self.conn.close()
		else:
			return {'code' : 5, 'message' : '提交参数不全'}

if __name__ == '__main__':
	u = Users()
	user_info = {
		'phone' : '15010220814',
		'passwd' : 'zuoloveyou',
	}
	print u.login(user_info)
	'''
	u = Users()
	
	print u.login(phone='15010220814',passwd='zuoloveyou')
	user_info = {
		'username' : 'wurui2',
		'phone' : '19010220895',
		'passwd' : 'zuoloveyou',
		'qq' : '2241661875'
	}
	print u.register(user_info=user_info)
	'''



